package com.eat.fish_service.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eat.common_utils.*;
import com.eat.fish_service.entity.Dao.Aquarium;
import com.eat.fish_service.entity.Dao.Expert;
import com.eat.fish_service.entity.Dao.User;
import com.eat.fish_service.entity.ExpertQuery;
import com.eat.fish_service.entity.UserQuery;
import com.eat.fish_service.entity.VO.EditChargeVo;
import com.eat.fish_service.entity.VO.UserVo;
import com.eat.fish_service.entity.newManager;
import com.eat.fish_service.mapper.UserMapper;
import com.eat.fish_service.service.AquariumService;
import com.eat.fish_service.service.ExpertService;
import com.eat.fish_service.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseCookie;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LWB
 * @since 2022-03-21
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AquariumService aquariumService;

    @Value("${uploadAvaterPath}")
    private String uploadPath;

    //邮箱发送的验证码
    private Integer code;

    //发送验证码的邮箱地址
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private ExpertService expertService;

    @Autowired
    private UserService userService;

    //小程序登录
    @Override
    public R login(User user) {
        //获取登录用户名和密码
        String username = user.getUsername();
        String password = user.getPassword();

        //判断用户名是否正确
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User userFromDB = baseMapper.selectOne(wrapper);

        if (userFromDB == null) {
            return R.error().code(ResultCode.NOT_REGISTER).message("该用户未注册");
        }

        //判断密码
        //把输入的密码进行加密后与数据库的密码进行比较
        if (!MD5.encrypt(password).equals(userFromDB.getPassword())) {
            return R.error().code(ResultCode.WRONG).message("密码输入错误，请重试");
        }
        return R.ok().data("userMes", userFromDB);
    }

    @Override
    public R register(User user) {
        System.out.println(user);

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        User user1 = baseMapper.selectOne(wrapper);
        if (user1 != null) {
            return R.error().code(ResultCode.ALREADY_EXISTS).message("该账号已被注册！");
        }
        user.setPassword(MD5.encrypt(user.getPassword()));
        baseMapper.insert(user);
        return R.ok();
    }

    @Override
    public R getStatus(String username) {
        //根据用户名查询用户身份
        User userFromDB = baseMapper.selectOne(new QueryWrapper<User>()
                .eq("username", username));
        //身份：1：普通用户  2：专家
        return R.ok().data("status", userFromDB.getStatus());
    }

    //原来的web页面登录
    @Override
    public R webLogin(UserVo userVo) {

//        log.info(userVo.toString());
        User user = baseMapper.selectOne(new QueryWrapper<User>()
                .eq("username", userVo.getUsername())
                .eq("password", MD5.encrypt(userVo.getPassword())));
        Integer status = user.getStatus();

        if (user == null) {
            return R.error().message("用户名或密码错误");
        }

        //jwt生成token,包含用户姓名
        String token = JwtUtils.getJwtToken(user.getUsername());

        //token存入redis,7天有效期，具体自己设置
        redisTemplate.opsForValue().set(userVo.getUsername(), token, Duration.ofDays(7));


        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("userStatus", status);
        map.put("userInfo", user);
        return R.ok().data(map);
    }

    //用于实现自动登录
    @Override
    public R webLogin(UserVo userVo, HttpServletRequest request, HttpServletResponse response) {
        User user = baseMapper.selectOne(new QueryWrapper<User>()
                .eq("username", userVo.getUsername())
                .eq("password", MD5.encrypt(userVo.getPassword())));
        Integer status = user.getStatus();

        if (user == null) {
            return R.error().message("用户名或密码错误");
        }

        //jwt生成token,包含用户姓名
        String token = JwtUtils.getJwtToken(user.getUsername());

        //token存入redis,7天有效期，具体自己设置
        redisTemplate.opsForValue().set(userVo.getUsername(), token, Duration.ofDays(7));


        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);  //返回token给浏览器
        map.put("userStatus", status);
        map.put("userInfo", user);
        return R.ok().data(map);
    }

    //自动登录获取用户信息，需要更新token和cookie
    @Override
    public R getUserMess(String username,HttpServletRequest request,HttpServletResponse response) {
        User user = baseMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        //jwt生成token,包含用户姓名
        String token = JwtUtils.getJwtToken(username);

        //token存入redis,7天有效期，具体自己设置
        redisTemplate.opsForValue().set(username, token, Duration.ofDays(7));

        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token); //返回token给浏览器
        map.put("userStatus", user.getStatus());
        map.put("userInfo", user);
        return R.ok().data(map).message("自动登录成功！");
    }

    @Override
    public R editCharge(EditChargeVo editChargeVo) {

        log.info(editChargeVo.toString());

        User user = baseMapper.selectOne(new QueryWrapper<User>()
                .eq("real_name", editChargeVo.getName())
                .eq("phone", editChargeVo.getPhone()));

        if (user == null || user.getStatus() != 3) {
            return R.error().message("负责人信息填写错误，请核对填写的姓名和电话！");
        }

        Aquarium aquarium = new Aquarium();
        aquarium.setId(editChargeVo.getAquariumId());
        aquarium.setCharge(editChargeVo.getName());

        aquariumService.updateById(aquarium);
        return R.ok();
    }

    @Override
    public R uploadAvater(MultipartFile pic, String id) {


        if (pic == null) return R.error().message("上传的图片为空！");

        String fileName = System.currentTimeMillis() + pic.getOriginalFilename();

        //如果第一次运行，需要创建一下目录
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File targetFile = new File(uploadPath, fileName);
        try {
            pic.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error().message("上传失败");
        }

        //服务器的ip和端口号
        String ipAndPort = IpAndPortUtil.getIpAndPort();
        String picUrl = "http://" + ipAndPort + "/getAvater/" + fileName;

        //更新用户表
        User user = new User();
        user.setId(id);
        user.setAvater(picUrl);
        baseMapper.updateById(user);

        return R.ok().data("picUrl", picUrl);
    }

    @Override
    public R updateUserMes(User user) {
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setRealName(user.getRealName());
        updateUser.setAvater(user.getAvater());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());

        //如果是专家要改真实姓名，专家表也要改
        User getByDB = baseMapper.selectById(user.getId());
        if (getByDB.getStatus() == 2 && user.getRealName() != null) {
            boolean update = expertService.update(new UpdateWrapper<Expert>().set("real_name", user.getRealName()).eq("real_name", getByDB.getRealName()));
            if (!update) {
                return R.error().message("更新失败");
            }
        }

        int update = baseMapper.updateById(updateUser);
        if (update == 1) {
            return R.ok();
        } else {
            return R.error().message("更新失败");
        }
    }

    @Override
    public R sendCode(String to, String id, HttpSession session) {
        code = RandomUtil.randomInt(100000, 999999);
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject("智慧鱼缸平台");
        simpleMailMessage.setText("【智慧鱼缸平台】您正在修改密码，验证码：" + code.toString() + "，2分钟内有效。");
        session.setAttribute(id, code.toString());
        session.setMaxInactiveInterval(120);
        javaMailSender.send(simpleMailMessage);
        return R.ok().message("已发送验证码");
    }

    @Override
    public R findSendCode(String to, String id, HttpSession session) {
        code = RandomUtil.randomInt(100000, 999999);
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject("智慧鱼缸平台");
        simpleMailMessage.setText("【智慧鱼缸平台】您正在找回密码，验证码：" + code.toString() + "，2分钟内有效。");
        session.setAttribute(id, code.toString());
        session.setMaxInactiveInterval(120);
        javaMailSender.send(simpleMailMessage);
        return R.ok().message("已发送验证码");
    }

    @Override
    public R findUserCondition(Long current, Long size, UserQuery userQuery) {
        //创建page
        Page<User> pageUser = new Page<>(current, size);
        //构建条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //多条件查询
        String realName = userQuery.getRealName();
        String phone = userQuery.getPhone();
        String TimeBegin = userQuery.getTimeBegin();
        String TimeEnd = userQuery.getTimeEnd();

        wrapper.eq("status", 1);
        if (!StringUtils.isEmpty(realName)) {
            wrapper.like("real_name", realName);
        }
        if (!StringUtils.isEmpty(phone)) {
            wrapper.eq("phone", phone);
        }
        if (!StringUtils.isEmpty(TimeBegin)) {
            wrapper.ge("gmt_create", TimeBegin);
        }
        if (!StringUtils.isEmpty(TimeEnd)) {
            wrapper.le("gmt_create", TimeEnd);
        }

        //调用方法实现查询
        userService.page(pageUser, wrapper);

        long total = pageUser.getTotal();//获取总记录数
        List<User> records = pageUser.getRecords();//获取分页后的list集合
        long pages = pageUser.getPages();
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("rows", records);
        if (current > pages) {
            return R.error().code(13).message("超过总页数");
        } else {
            return R.ok().data(map);
        }
    }

    @Override
    public R findExpertCondition(Long current, Long size, UserQuery userQuery) {
        //创建page
        Page<User> pageUser = new Page<>(current, size);
        //构建条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //多条件查询
        String realName = userQuery.getRealName();
        String phone = userQuery.getPhone();
        String TimeBegin = userQuery.getTimeBegin();
        String TimeEnd = userQuery.getTimeEnd();

        wrapper.eq("status", 2);
        if (!StringUtils.isEmpty(realName)) {
            wrapper.like("real_name", realName);
        }
        if (!StringUtils.isEmpty(phone)) {
            wrapper.eq("phone", phone);
        }
        if (!StringUtils.isEmpty(TimeBegin)) {
            wrapper.ge("gmt_create", TimeBegin);
        }
        if (!StringUtils.isEmpty(TimeEnd)) {
            wrapper.le("gmt_create", TimeEnd);
        }

        //调用方法实现查询
        userService.page(pageUser, wrapper);

        long total = pageUser.getTotal();//获取总记录数
        List<User> records = pageUser.getRecords();//获取分页后的list集合
        long pages = pageUser.getPages();
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("rows", records);
        if (current > pages) {
            return R.error().code(13).message("超过总页数");
        } else {
            return R.ok().data(map);
        }
    }

    @Override
    public R findManagerCondition(Long current, Long size, UserQuery userQuery) {
        //创建page
        Page<User> pageUser = new Page<>(current, size);
        //构建条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //多条件查询
        String realName = userQuery.getRealName();
        String phone = userQuery.getPhone();
        String TimeBegin = userQuery.getTimeBegin();
        String TimeEnd = userQuery.getTimeEnd();

        wrapper.eq("status", 3);
        if (!StringUtils.isEmpty(realName)) {
            wrapper.like("real_name", realName);
        }
        if (!StringUtils.isEmpty(phone)) {
            wrapper.eq("phone", phone);
        }
        if (!StringUtils.isEmpty(TimeBegin)) {
            wrapper.ge("gmt_create", TimeBegin);
        }
        if (!StringUtils.isEmpty(TimeEnd)) {
            wrapper.le("gmt_create", TimeEnd);
        }

        //调用方法实现查询
        userService.page(pageUser, wrapper);

        long total = pageUser.getTotal();//获取总记录数
        List<User> records = pageUser.getRecords();//获取分页后的list集合
        long pages = pageUser.getPages();
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("rows", records);
        if (current > pages) {
            return R.error().code(13).message("超过总页数");
        } else {
            return R.ok().data(map);
        }
    }

    @Override
    public R addManager(newManager newManager, int status) {
        User user = new User();
        if (!StringUtils.isEmpty(newManager.getAvater())) {
            user.setAvater(newManager.getAvater());
        }
        user.setStatus(status);
        user.setUsername(newManager.getUsername());
        user.setRealName(newManager.getRealName());
        user.setPhone(newManager.getPhone());
        user.setEmail(newManager.getEmail());
        user.setPassword(newManager.getPassword());
        boolean save = userService.save(user);
        if (save) {
            return R.ok();
        } else {
            return R.error().message("添加失败");
        }

    }

    @Override
    public R deleteManager(String UserId) {
        boolean b = userService.removeById(UserId);
        if (b) {
            return R.ok();
        } else {
            return R.error().message("删除失败失败");
        }
    }
}